package com.guapi.Aspect;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.guapi.exception.SelfException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class ServiceLogAspect {
    private static final Log log = LogFactory.get(ServiceLogAspect.class);


    @Pointcut("execution(* com.guapi.controller.*.*(..))&&!execution(* com.guapi.controller.SystemInfoController.*(..))")
    public void controllerPoint() {
    }

    @Before("controllerPoint()")
    public void before(JoinPoint joinPoint) {
        //用户[1.2.3.4]在[xxx]访问了[com.guapi.service.xxx()]
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //此处有可能报空指针异常，因为在Producer和Consumer中直接调用了Service
        //与正常使用Controller调用Service不同。
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        log.info(String.format("用户[%s],在[%s]访问了[%s].", ip, DateUtil.now(), target));
        //log.info(String.format("用户:[%s],ip:[%s],在[%s]访问了[%s].", ip, DateUtil.now(), target));
    }

    @Pointcut("execution(* com.guapi.mapper.SelfBaseMapper.*(..))")
    public void userPoint() {
    }

    @Before("userPoint()")
    public void beforeMapper(JoinPoint joinPoint) {
        System.out.println(joinPoint);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNull(attributes)) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String header = request.getHeader("X-SHOW");
        if (ObjectUtil.isNull(header)) {
            return;
        }
        if (header.equalsIgnoreCase("show")) {
            if (StrUtil.containsAnyIgnoreCase(joinPoint.toString(), "update", "delete", "save", "insert")) {
                throw new SelfException("演示账户无法进行修改操作！");
            }
        }
    }

}
